<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/// ...
class TranslateController extends AppController
{
	public $uses             = false;
	public $components       = array('Locker');
	public $restrict_actions = array('index', 'read', 'save');
	
	/// Displays a list of files to translate.
	function index()
	{
		$this->pageTitle = _('Translations');
	}
	
	/**
	 * Display or saves (on POST) a file for translation.
	 * 
	 * @param $file String
	 * @param $lang String
	 * @param $ref_lang String
	 */
	function file($file, $lang, $ref_lang=null)
	{
		$this->Locker->lock("translation.$lang.".md5($file));
		$PO = $this->read_po($file, $lang);
		
		$fuzzy = isset($this->params['form']['fuzzy']) ? $this->params['form']['fuzzy'] : array();
		
		if (!empty($this->data) and $PO->save($this->data, $fuzzy))
		{
			# SVN commit
#			$svn_ci_message = sprintf('Updated translation: %s', $lang);
#			chdir(dirname($this->get_path($file, $lang)));
#			`svn ci -m {$svn_ci_message}`;
			
			# finish
			$this->Locker->unlock();
			$this->flash(_('Translation saved.'), $this->Config->plugin['base_url']);
		}
		
		# form
		if ($ref_lang !== null)
		{
			$ref_PO = $this->read_po($file, $ref_lang);
			$this->set('ref_lang', $ref_lang);
			$this->set('ref_PO', $ref_PO);
		}
		$this->set(array(
			'PO'   => $PO,
			'lang' => $lang,
			'file' => $file
		));
		$this->pageTitle = sprintf(_('Translation of %s: %s'), $file,
			strtolower($this->Locale->getLanguage($lang)));
		$this->render("file");
	}
	
	function cancel($file, $lang)
	{
		$this->Locker->unlock("translation.$lang.".md5($file));
		HTTP::redirect($this->Config->plugin['base_url']);
	}
	
	/**
	 * Returns the path to a PO file.
	 * 
	 * @return String
	 * @param $file String
	 * @param $lang String
	 */
	private function get_path($file, $lang)
	{
		$locale = $this->Locale->get($lang);
		return $this->Config->plugin['path'].$file.DS.$locale.DS."$file.po";
	}
	
	/**
	 * Parses a PO file.
	 * 
	 * @return Gettext_PO
	 * @param $file String
	 * @param $lang String
	 */
	private function read_po($file, $lang)
	{
		Load::libs('gettext');
		$path = $this->get_path($file, $lang);
		$PO = new Gettext_PO($path);
		return $PO;
	}
}

?>